<?php
/**
 * 核心库
 * User: dxk
 * Date: 2020/07/15
 */
namespace App\Model;

use App\Traits\CacheTrait;
use App\Traits\SingleInstanceTrait;
use Illuminate\Database\Connection;
use DB;

class CoreModel
{
    use SingleInstanceTrait, CacheTrait;

    //-------------数据库-------------
    /**
     * 数据库连接对象
     * @var Connection
     */
    private $connection;
    private string $connection_name = '';//数据库连接名
    private string $db_tag = '';//数据库分类
    private int $is_slave = 0;//是否从库
    protected string $table = '';//数据库表

    //---------------缓存--------------
    /**
     * DBModel constructor.
     * @param string $db_tag
     * @param bool $is_slave
     * @throws \Exception
     */
    protected function __construct(string $db_tag = 'core', bool $is_slave = false)
    {
        unset($this->connection);
        $this->connection_name = $db_tag;
        $this->db_tag = $db_tag;
        $this->is_slave = (int)$is_slave;
        if ($this->is_slave) {
            $this->connection_name = $this->connection_name . '_' . $this->is_slave;
        }
        $this->cache_prefix = $this->db_tag . ':' . $this->table . ':';
        $this->debug = config('app.debug');
        $this->cache_time = config('sys.cache_time');
    }

    /**
     * 获取数据库连接
     * @return Connection
     */
    public function getConnection(): Connection
    {
        if (empty($this->connection)) {
            $this->connection = DB::connection($this->connection_name);
        }
        return $this->connection;
    }

    /**
     * 获取连接表对象
     * @param string $table
     * @param $as
     * @return \Illuminate\Database\Query\Builder|void
     */
    public function getConnectionTable(string $table = '', $as = null)
    {
        if (empty($table)) {
            $table = $this->table;
        }
        if (empty($table)) {
            die('表信息错误' . static::class);
        }
        return $this->getConnection()->table($table, $as);
    }
}
